<template>
    <div class="play">
        <div :class="['hand',{handHide:!isLock},{handShow:isLock}]" title="展开播放条">
            <div class="lock" @click="reverseLock" :title="isLock?'隐藏':'锁定'">
                <i :class="['iconfont',{'icon-unlock':!isLock},{'icon-lock':isLock}]"></i>
            </div>
            <div class="showBar"></div>
        </div>
        <div :class="['playBar',{playbarShow:isLock},{playbarHide:!isLock}]">
            <div class="container">
                <div class="btns">
                    <i class="iconfont icon-play_pre" title="上一首" @click="playNextOrPre(0)"></i>
                    <i :class="['iconfont' ,{'icon-play':!isPlay},{'icon-stop':isPlay}]"
                       :title="isPlay?'暂停':'播放'"
                       @click="playOrPause"></i>
                    <i class="iconfont icon-play_next" title="下一首" @click="playNextOrPre(1)"></i>
                </div>
                <div class="img">
                    <router-link to="/">
                        <img :src="currentMusicCoverUrl?currentMusicCoverUrl:whiteImg"/>
                    </router-link>
                </div>
                <div class="playProgress">
                    <div class="details">
                        <router-link to="/" class="musicName" :title="currentMusicName?currentMusicName:''">
                            {{currentMusicName?currentMusicName:''}}
                        </router-link>
                        <router-link v-show="currentMusicMv!=0" to="/" class="mv" title="MV">
                            <span class="iconfont icon-MV"></span>
                        </router-link>
                        <router-link to="/" class="musicArtist"
                                     :title="currentMusicDetail?currentMusicDetail.ar[0].name:''">
                            {{currentMusicArtist?currentMusicArtist:''}}
                        </router-link>
                    </div>
                    <el-slider :step="0.1"
                               :format-tooltip="formatTooltip"
                               v-model="pTime"
                               :show-tooltip="totalTime&&playedTime?true:false"
                               @change="ch"></el-slider>
                </div>
                <div class="time">
                    <span v-show="totalTime&&playedTime"><span style="color:#969696">{{playedTime}}&nbsp;</span>/&nbsp;{{totalTime}}</span>
                    <span v-show="!totalTime||!playedTime">00:00&nbsp;/&nbsp;00:00</span>
                </div>
                <div class="player_control">

                    <div v-show="showVol"
                         class="volume"
                         @click.stop>
                        <el-slider
                                :show-tooltip="true"
                                v-model="volume"
                                vertical
                                @change="saveVolume"
                                height="100px">
                        </el-slider>
                    </div>
                    <!--由于下文有document的click事件，这里一定要阻止冒泡-->
                    <span :class="['iconfont' ,{'icon-volume':volume!=0},{'icon-SoundNovolume':volume==0}]"
                          @click.stop="showVolume"></span>
                    <span @click="changePlayMode"
                          :class="['iconfont',{'icon-repeat_one':playMode=='single'},{'icon-repeat':playMode=='order'},{'icon-shuffle':playMode=='shuffle'}]"></span>
                    <span @click.stop="togglePlayList" class="iconfont icon-playlist"></span>
                    <span @click.stop="togglePlayList" class="listNum">{{playListNum}}</span>
                </div>
            </div>
        </div>
        <bottomPlayList v-show="playListShow" :show="playListShow"></bottomPlayList>
    </div>
</template>

<script>
    //vue加载mp3必须用require引入，不能直接写src
    import {mapState} from 'vuex';
    import musicApi from "../request/musicApi";
    import bottomPlayList from './bottomPlayList'

    export default {
        name: "player",
        components: {bottomPlayList},
        data() {
            return {
                isLock: false,
                lastPlayMusicId: '',
                whiteImg: require('../assets/default_album.jpg'),
                pTime: 0,
                volume: 50,
                showVol: false,
                totalTime: '',
                playedTime: '',
                playMode: 'order',
                settings: {//为了缓存相关播放设置，如音量，是否lock
                    isLock: false,
                    volume: 50,
                    playMode: 'order'
                },
                bufferedTime: 0,
                playListShow: false
            }
        },
        methods: {
            togglePlayList() {
                this.playListShow = !this.playListShow;
            },
            saveVolume() {
                this.$set(this.settings, 'volume', this.volume);
                localStorage.setItem('settings', JSON.stringify(this.settings));
            },
            changePlayMode() {
                let index = this.$store.state.playMode.indexOf(this.playMode);
                this.playMode = this.$store.state.playMode[(index + 1) % this.$store.state.playMode.length];
                // this.settings.playMode = this.playMode;
                this.$set(this.settings, 'playMode', this.playMode);
                localStorage.setItem('settings', JSON.stringify(this.settings));
            },
            formatTooltip(v) {
                if (this.totalTime && this.playedTime) {
                    let ct = v / 100 * this.duration;
                    let playedMin = Math.floor(Math.ceil(ct) / 60);
                    let playedSec = Math.ceil(ct) % 60;
                    playedMin = (playedMin >= 10 ? '' : '0') + playedMin;
                    playedSec = (playedSec >= 10 ? '' : '0') + playedSec;
                    return playedMin + ':' + playedSec;
                } else
                    return;
            },
            //toggle volumeBar
            showVolume() {
                if (window.navigator.appVersion.indexOf('iPhone') != -1 || window.navigator.appVersion.indexOf('iPad') != -1) {
                    this.$message({
                        showClose: true,
                        message: '由于系统限制，IOS用户请手动调节系统音量',
                        type: 'warning'
                    });
                    return;
                }
                this.showVol = !this.showVol;
            },
            //播放暂停
            playOrPause() {
                let player = document.getElementById('audioPlayer');
                if (this.$store.state.currentSongId == '') {
                    this.$message.error('没有可播放的音乐');
                    return;
                }
                if (this.isPlay)
                    document.getElementById('audioPlayer').pause();
                else {
                    if (!this.currentMusicUrl) {
                        this.$alert('版权问题，暂时无法播放，请到官网购买', '提示', {
                            confirmButtonText: '确定'
                        });
                        return;
                    }
                    player.play();
                    player.currentTime = this.pTime / 100 * this.duration;
                }
                this.$store.commit('setPlayStatus', !this.isPlay)
            },
            //toggle lock
            reverseLock() {
                this.isLock = !this.isLock;
                this.$set(this.settings, 'isLock', this.isLock);
                // this.settings.isLock = this.isLock;
                // localStorage.setItem('isLock', this.isLock);
                localStorage.setItem('settings', JSON.stringify(this.settings));
            },
            //音乐进度条相关逻辑
            ch(v) {
                if (!this.currentMusicUrl) {
                    this.$alert('版权问题，暂时无法播放，请到官网购买', '提示', {
                        confirmButtonText: '确定'
                    });
                    return;
                }
                this.$store.commit('setCurrentPlayTime', v / 100 * this.duration);

                if (this.isPlay) {
                    document.getElementById('audioPlayer').currentTime = this.$store.state.currentPlayTime;
                }
            },
            //初始化音乐播放器，注册相关事件监听
            initPlayer() {
                let store = this.$store;
                let player = document.getElementById('audioPlayer');
                player.src = this.currentMusicUrl;
                player.volume = this.volume / 100;
                player.addEventListener('durationchange', () => {
                    store.commit('setDuration', player.duration);
                    let totalMin = Math.floor(Math.ceil(player.duration) / 60);
                    let totalSec = Math.ceil(player.duration) % 60;
                    totalMin = (totalMin >= 10 ? '' : '0') + totalMin;
                    totalSec = (totalSec >= 10 ? '' : '0') + totalSec;
                    this.totalTime = totalMin + ':' + totalSec;
                }, false);
                player.addEventListener('canplay', () => {
                    if (!this.playedTime && this.isPlay) {
                        player.currentTime = this.duration * this.pTime / 100;//适配ios currentTime设置必须在play以后
                    }
                    let store = this.$store;
                    if (store.state.playList.length != 0) {
                        for (let i = 0; i < store.state.playList.length; i++) {
                            if (this.currentSongId == store.state.playList[i].id) {
                                localStorage.setItem('latPlayMusicIndex', '' + i);
                                store.commit('setCurrentMusicIndex', i);
                                break;
                            }
                        }
                    }
                }, false);
                player.addEventListener('timeupdate', () => {
                    store.commit('setCurrentPlayTime', player.currentTime);//更新当前播放时间
                    let playedMin = Math.floor(Math.ceil(player.currentTime) / 60);
                    let playedSec = Math.ceil(player.currentTime) % 60;
                    playedMin = (playedMin >= 10 ? '' : '0') + playedMin;
                    playedSec = (playedSec >= 10 ? '' : '0') + playedSec;
                    this.playedTime = playedMin + ':' + playedSec;
                    this.pTime = store.state.currentPlayTime / store.state.duration * 100;

                }, false);
                player.addEventListener('ended', () => {
                    let store = this.$store;
                    let index = '';
                    let player = document.getElementById('audioPlayer');
                    //获取歌曲所在列表index
                    for (let i = 0; i < store.state.playList.length; i++) {
                        if (store.state.playList[i].id == this.currentSongId) {
                            index = i;
                            break;
                        }
                    }
                    // store.commit('setPlayStatus', false);//更新播放结束后的播放状态
                    if (this.playMode == 'order') {
                        player.muted = true;
                        let s = this.$store.state.playList[(index + 1) % store.state.playList.length];
                        musicApi.getMusicUrl({id: s.id})
                            .then(res => {
                                if (res.data.code == 200) {
                                    if (!res.data.data[0].url) {
                                        this.$alert('版权问题，暂时无法播放，请到官网购买', '提示', {
                                            confirmButtonText: '确定'
                                        });
                                        player.muted = false;
                                        return;
                                    }
                                    store.commit('setCurrentSongId', s.id);
                                    store.commit('setCurrentMusicMv', s.mv);
                                    store.commit('setCurrentMusicArtist', s.artist);
                                    store.commit('setCurrentMusicName', s.name);
                                    store.commit('setCurrentMusicCoverUrl', s.picUrl);
                                    store.commit('setCurrentMusicUrl', res.data.data[0].url);
                                    player.src = res.data.data[0].url;
                                    if (this.isPlay) {
                                        player.play();
                                    }
                                    player.muted = false;
                                }
                            });
                    }
                    if (this.playMode == 'shuffle') {
                        let num = this.$store.state.playList.length;
                        let random = Math.floor(Math.random() * num);
                        while (random == index) {
                            random = Math.floor(Math.random() * num);
                        }
                        player.muted = true;
                        let s = this.$store.state.playList[random];
                        musicApi.getMusicUrl({id: s.id})
                            .then(res => {
                                if (res.data.code == 200) {
                                    if (!res.data.data[0].url) {
                                        this.$alert('版权问题，暂时无法播放，请到官网购买', '提示', {
                                            confirmButtonText: '确定'
                                        });
                                        player.muted = false;
                                        return;
                                    }
                                    store.commit('setCurrentSongId', s.id);
                                    store.commit('setCurrentMusicMv', s.mv);
                                    store.commit('setCurrentMusicArtist', s.artist);
                                    store.commit('setCurrentMusicName', s.name);
                                    store.commit('setCurrentMusicCoverUrl', s.picUrl);
                                    store.commit('setCurrentMusicUrl', res.data.data[0].url);
                                    player.src = res.data.data[0].url;
                                    if (this.isPlay) {
                                        player.play();
                                    }
                                    player.muted = false;
                                }
                            });
                    }
                }, false);
                player.addEventListener('play', () => {
                    document.title = '▶ ' + this.$store.state.currentMusicName;
                    store.commit('setPlayStatus', true);
                }, false);
                player.addEventListener('pause', () => {
                    document.title = this.$route.meta.title
                }, false);
                //player.preload = 'auto';//自动加载（必须设置否则buffered时间不会往后加载）
            },
            playNextOrPre(type) {//0:上一首，1:下一首
                if(this.playList.length==0){
                    this.$message({
                        showClose: true,
                        message: '播放列表为空',
                        type: 'error'
                    });
                    return ;
                }
                let store = this.$store;
                let index = '';
                let player = document.getElementById('audioPlayer');
                //获取歌曲所在列表index
                for (let i = 0; i < store.state.playList.length; i++) {
                    if (store.state.playList[i].id == this.currentSongId) {
                        index = i;
                        break;
                    }
                }
                if (type == 0) {
                    if (this.playMode == 'order' || this.playMode == 'single') {
                        player.muted = true;
                        let s = this.$store.state.playList[(store.state.playList.length + index - 1) % store.state.playList.length];
                        musicApi.getMusicUrl({id: s.id})
                            .then(res => {
                                if (res.data.code == 200) {
                                    if (!res.data.data[0].url) {
                                        this.$alert('版权问题，暂时无法播放，请到官网购买', '提示', {
                                            confirmButtonText: '确定'
                                        });
                                        player.muted = false;
                                        return;
                                    }
                                    store.commit('setCurrentSongId', s.id);
                                    store.commit('setCurrentMusicMv', s.mv);
                                    store.commit('setCurrentMusicArtist', s.artist);
                                    store.commit('setCurrentMusicName', s.name);
                                    store.commit('setCurrentMusicCoverUrl', s.picUrl);
                                    store.commit('setCurrentMusicUrl', res.data.data[0].url);
                                    player.src = res.data.data[0].url;
                                    if (this.isPlay) {
                                        player.play();

                                    }
                                    else {
                                        player.play();
                                        player.currentTime = 0;
                                        player.pause();
                                        this.pTime = 0;
                                    }
                                    player.muted = false;
                                }
                            });
                    }
                    else {
                        let num = this.$store.state.playList.length;
                        let random = Math.floor(Math.random() * num);
                        while (random == index) {
                            random = Math.floor(Math.random() * num);
                        }
                        player.muted = true;
                        let s = this.$store.state.playList[random];
                        musicApi.getMusicUrl({id: s.id})
                            .then(res => {
                                if (res.data.code == 200) {
                                    if (!res.data.data[0].url) {
                                        this.$alert('版权问题，暂时无法播放，请到官网购买', '提示', {
                                            confirmButtonText: '确定'
                                        });
                                        player.muted = false;
                                        return;
                                    }
                                    store.commit('setCurrentSongId', s.id);
                                    store.commit('setCurrentMusicMv', s.mv);
                                    store.commit('setCurrentMusicArtist', s.artist);
                                    store.commit('setCurrentMusicName', s.name);
                                    store.commit('setCurrentMusicCoverUrl', s.picUrl);
                                    store.commit('setCurrentMusicUrl', res.data.data[0].url);
                                    player.src = res.data.data[0].url;
                                    if (this.isPlay) {
                                        player.play();
                                    }
                                    else {
                                        player.play();
                                        player.currentTime = 0;
                                        player.pause();
                                        this.pTime = 0;
                                    }
                                    player.muted = false;
                                }
                            });
                    }
                }
                if (type == 1) {
                    if (this.playMode == 'order' || this.playMode == 'single') {
                        player.muted = true;
                        let s = this.$store.state.playList[(index + 1) % store.state.playList.length];
                        musicApi.getMusicUrl({id: s.id})
                            .then(res => {
                                if (res.data.code == 200) {
                                    if (!res.data.data[0].url) {
                                        this.$alert('版权问题，暂时无法播放，请到官网购买', '提示', {
                                            confirmButtonText: '确定'
                                        });
                                        player.muted = false;
                                        return;
                                    }
                                    store.commit('setCurrentSongId', s.id);
                                    store.commit('setCurrentMusicMv', s.mv);
                                    store.commit('setCurrentMusicArtist', s.artist);
                                    store.commit('setCurrentMusicName', s.name);
                                    store.commit('setCurrentMusicCoverUrl', s.picUrl);
                                    store.commit('setCurrentMusicUrl', res.data.data[0].url);
                                    player.src = res.data.data[0].url;
                                    if (this.isPlay) {
                                        player.play();
                                    }
                                    else {
                                        player.play();
                                        player.currentTime = 0;
                                        player.pause();
                                        this.pTime = 0;
                                    }

                                    player.muted = false;
                                }
                            });
                    }
                    else {
                        let num = this.$store.state.playList.length;
                        let random = Math.floor(Math.random() * num);
                        while (random == index) {
                            random = Math.floor(Math.random() * num);
                        }
                        player.muted = true;
                        let s = this.$store.state.playList[random];
                        musicApi.getMusicUrl({id: s.id})
                            .then(res => {
                                if (res.data.code == 200) {
                                    if (!res.data.data[0].url) {
                                        this.$alert('版权问题，暂时无法播放，请到官网购买', '提示', {
                                            confirmButtonText: '确定'
                                        });
                                        player.muted = false;
                                        return;
                                    }
                                    store.commit('setCurrentSongId', s.id);
                                    store.commit('setCurrentMusicMv', s.mv);
                                    store.commit('setCurrentMusicArtist', s.artist);
                                    store.commit('setCurrentMusicName', s.name);
                                    store.commit('setCurrentMusicCoverUrl', s.picUrl);
                                    store.commit('setCurrentMusicUrl', res.data.data[0].url);
                                    player.src = res.data.data[0].url;
                                    if (this.isPlay) {
                                        player.play();
                                    }
                                    else {
                                        player.play();
                                        player.currentTime = 0;
                                        player.pause();
                                        this.pTime = 0;
                                    }
                                    player.muted = false;
                                }
                            });
                    }
                }
            }
        },
        computed: {
            ...mapState({
                isPlay: (state) => state.isPlay,
                coverUrl: (state) => state.coverUrl,
                duration: (state) => state.duration,
                currentSongId: (state) => state.currentSongId,
                currentMusicUrl: (state) => state.currentMusicUrl,
                currentPlayTime: (state) => state.currentPlayTime,
                currentMusicDetail: (state) => state.currentMusicDetail,
                currentMusicCoverUrl: (state) => state.currentMusicCoverUrl,
                currentMusicArtist: (state) => state.currentMusicArtist,
                currentMusicName: (state) => state.currentMusicName,
                currentMusicIndex: (state) => state.currentMusicIndex,
                currentMusicMv: (state) => state.currentMusicMv,
                playList: (state) => state.playList,
                playListNum: (state) => state.playList.length
            }),
        },
        watch: {
            //监听音量变化，因为音量随进度条改变，进度条change是在鼠标松开后回调，不符合需求
            volume(newV, oldV) {
                this.volume = newV;
                //audio的volume范围是[0,1]
                document.getElementById('audioPlayer').volume = this.volume / 100;
            },
            playMode(newV) {
                if (newV == 'single')
                    document.getElementById('audioPlayer').loop = true;
                else
                    document.getElementById('audioPlayer').loop = false;
            },
            $route(){
                this.playListShow=false;
            }
        },
        created() {
            let store = this.$store;
            //点击别处隐藏volumeBar，在div.volume处设置@click.stop组织冒泡事件发生
            document.onclick = (e) => {
                this.showVol = false;
                this.playListShow = false;
            }
            //加载缓存localstorage
            //加载记录的volume值
            if (localStorage.getItem('settings')) {
                let settings = JSON.parse(localStorage.getItem('settings'));
                this.playMode = settings.playMode;
                this.volume = settings.volume;
                this.isLock = settings.isLock;
                this.$set(this.settings, 'playMode', this.playMode);
                this.$set(this.settings, 'isLock', this.isLock);
                this.$set(this.settings, 'volume', this.volume);
            }
            //加载播放列表
            if (localStorage.getItem('playList')) {
                let l = JSON.parse(localStorage.getItem('playList'));
                store.commit('setMusicPlayList', l);
            }
            if (localStorage.getItem('latPlayMusicIndex')) {
                let obj = store.state.playList[parseInt(localStorage.getItem('latPlayMusicIndex'))];
                store.commit('setCurrentSongId', obj.id);
                store.commit('setCurrentMusicMv', obj.mv);
                store.commit('setCurrentMusicArtist', obj.artist);
                store.commit('setCurrentMusicName', obj.name);
                store.commit('setCurrentMusicCoverUrl', obj.picUrl);
                musicApi.getMusicUrl({id: obj.id})
                    .then(res => {
                        if (res.data.code == 200) {

                            store.commit('setCurrentMusicUrl', res.data.data[0].url);
                            this.initPlayer();
                        }
                    });
            } else
                this.initPlayer();
        },
        mounted() {

        }
    }
</script>

<style lang="scss">
    @import "../assets/fonts/iconfont.css";
    #audioPlayer {
        display: none;
    }

    .handHide {
        bottom: 0px;
    }

    .playbarHide {
        top: 53px;
    }

    .handShow {
        bottom: 53px;
    }

    .playbarShow {
        top: 0px;
    }

    .play {
        width: 100%;
        position: fixed;
        bottom: 0px;
        height: 53px;
        z-index: 2;
        .hand {
            .lock {
                cursor: pointer;
                text-align: center;
                border-radius: 10px;
                width: 40px;
                float: right;
                position: relative;
                top: 3px;
                background: #2E2E2E;
                z-index: 3;
                border: none;
                .iconfont {
                    color: #8C8A8B;
                    &:hover {
                        color: #fff;
                    }
                }
            }
            height: 20px;
            width: 100%;
            /*bottom: 0px;*/
            transition: bottom 1s;
            position: absolute;
            .showBar {
                position: absolute;
                top: 18px;
                height: 2px;
                width: 100%;
                background: linear-gradient(to top, #000, #fff);
            }
        }
        .playBar {
            position: absolute;
            width: 100%;
            height: 53px;
            /*top: 53px;*/
            transition: top 1s;
            background: #2E2E2E;
            div.container {
                div.btns {
                    float: left;
                    line-height: 53px;
                    i {
                        cursor: pointer;
                        color: #fff;
                        display: inline-block;
                        width: auto;
                        margin-right: 10px;
                        &:nth-of-type(even) {
                            font-size: 30px;
                        }
                        &:nth-of-type(odd) {
                            font-size: 25px;
                        }
                    }
                }
                div.img {
                    float: left;
                    z-index: 3;
                    width: 34px;
                    height: 53px;
                    line-height: 53px;
                    img {
                        width: 34px;
                        height: 35px;
                    }
                }
            }
        }
        &:hover {
            div.hand {
                bottom: 53px;
            }
            div.playBar {
                top: 0px;
            }
        }
    }

    .playProgress {
        margin-left: 10px;
        float: left;
        width: 493px;
        .details {
            width: 100%;
            height: 20px;
            a {
                color: #fff;
                display: inline-block;
                margin-right: 5px;
            }
            a.musicName{
                width:auto;
                max-width:200px;
                white-space: nowrap;
                overflow: hidden;
                text-overflow:ellipsis;
            }
            a.mv {
                text-decoration: none;
                span {
                    font-size: 20px;
                }
            }
            a.musicArtist {
                margin-left: 5px;
                font-size: 10px;
            }
        }
        .el-slider {
            width: 100%;
            .el-slider__runway {
                background-color: #191919;
            }

        }
    }

    div.time {
        margin-left: 10px;
        float: left;
        color: #6F6F6F;
        height: 53px;
        font-size: 10px;
        padding-top: 30px;
    }

    div.player_control {
        position: relative;
        margin-left: 20px;
        float: left;
        line-height: 53px;
        height: 53px;
        color: #939393;
        div.volume {
            width: auto;
            height: 120px;
            position: absolute;
            left: -8px;
            top: -120px;
            background: rgba(#2A2A2A, 0.9);
            z-index: 3;
            .el-slider {
                margin-top: 10px;
            }
        }
        span {
            font-size: 22px;
            cursor: pointer;
            display: inline-block;
        }
        span:not(.icon-playlist) {
            margin-right: 10px;
        }
        span.listNum {
            border-radius: 0px 10px 10px 0px;
            height: 20px;
            width: 40px;
            line-height: 20px;
            background: #1F1F1F;
            color: #666666;
            text-align: center;
            font-size: 10px;
        }
        span:not(.listNum):hover {
            color: #CFCFCF;
        }
    }

</style>